package mgo

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"reflect"
)

func (this *Factory) GetIsEventOn() bool {
	return this.IsEventOn
}

func (this *Factory) SetEventOn() *Factory {
	this.IsEventOn = true
	return this
}

func (this *Factory) SetEventOff() {
	this.IsEventOn = false
}

func (this *Factory) Trigger(eventName string, data interface{}) {
	if this.IsEventOn {
		ez.DispatchToMany(eventName, data, this.GetCtx())
	}
}
func (this *Factory) TriggerNew(md interface{}) {
	this.Trigger(fmt.Sprintf("%sAfterCreate", GetModelPkgAndName(md)), md)
}
func (this *Factory) TriggerBeforeCreate(md interface{}) {
	this.Trigger(fmt.Sprintf("%sBeforeCreate", GetModelPkgAndName(md)), md)
}
func (this *Factory) TriggerAfterCreate(md interface{}) {
	this.Trigger(fmt.Sprintf("%sAfterCreate", GetModelPkgAndName(md)), md)
}
func (this *Factory) TriggerBeforeUpdate(md interface{}) {
	this.Trigger(fmt.Sprintf("%sBeforeUpdate", GetModelPkgAndName(md)), md)
}
func (this *Factory) TriggerAfterUpdate(md interface{}) {
	this.Trigger(fmt.Sprintf("%sAfterUpdate", GetModelPkgAndName(md)), md)
}
func (this *Factory) TriggerDelete(md interface{}) {
	this.Trigger(fmt.Sprintf("%sDelete", GetModelPkgAndName(md)), md)
}

func (this *Factory) TriggerUnDelete(md interface{}) {
	this.Trigger(fmt.Sprintf("%sUnDelete", GetModelPkgAndName(md)), md)
}

func (this *Factory) TriggerDestroy(md interface{}) {
	this.Trigger(fmt.Sprintf("%Destroy", GetModelPkgAndName(md)), md)
}

func GetModelPkgAndName(md interface{}) string {
	t := reflect.TypeOf(md)
	prefix := t.String()
	if prefix[:1] == "*" {
		prefix = prefix[1:]
	}
	return prefix
}
